<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>socket demo</title>
</head>
<body>
    <h2>学说话的tom 猫</h2>
    <div><label>消息内容(服务端接受到消息并原样返回)：</label><p id="serverMessage"></p></div>
    <div><label>我对自己说(游览器向服务端发送消息)：</label><input id="sendMessage" type="text" />&nbsp;&nbsp;&nbsp;&nbsp;<button onclick="send()">发送</button></div>
 
<script type="text/javascript">
 
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket('ws://localhost:8080/sbe/websocket');
    }else{
        alert("该游览器不知此WebSocket");
    }
    //websocket 链接成功后进行触发
    websocket.onopen = function (event){
        console.log("建立链接。。。。");
    }
    //websocket 链接关闭的进行触发
    websocket.onclose = function (event){
        console.log("关闭链接。。。。");
    }
    //接收到消息的进行触发
    websocket.onmessage = function(event){
        var serverMessage = document.getElementById("serverMessage");
        serverMessage.innerHTML= event.data;
        console.log("收到消息");
    }
 
    //连接发生错误的进行触发
    websocket.onerror = function(evt)
    {
        console.log("WebSocketError!");
    }
    //当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function (){
        websocket.close();
    }
    //关闭websocket连接
    function closeWebSocket(){
        websocket.close();
    }
    //发送消息
    function send(){
        var sendIput = document.getElementById("sendMessage");
        var sendMessage = sendIput.value;
        if(sendMessage.trim() == ""){
            alert("请输入发送消息！")
            return;
        }
        websocket.send(sendMessage);
    }
 
</script>
</body>
</html>